﻿/********************************************************
    * Project Name   : VAdvantage
    * Class Name     : InfoAsset
    * Purpose        : Asset Information
    * Class Used     : info
    * Chronological    Development
    * Raghunandan     23-Dec-2010
******************************************************/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using System.Windows.Forms;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Framework;

namespace VAdvantage.Search
{
    public class InfoAsset : Info
    {
        #region Private Variable

        string _queryValue = "";
        private const int HEIGHT = 23;
        //controls
        private VLabel lblKeyValue = new VLabel();
        private VTextBox txtValue = new VTextBox(HEIGHT);
        private VLabel lblName = new VLabel();
        private VTextBox txtName = new VTextBox(HEIGHT);
        private VLabel lblBPartner_ID = new VLabel();
        private VTextBoxButton vBPartner_ID;
        private VLabel lblProduct_ID = new VLabel();
        private VTextBoxButton vProduct_ID;
        private Logging.VLogger log = Logging.VLogger.GetVLogger(typeof(MOrderLine).FullName);

        // From Clause             
        private static String _assetFROM = "A_ASSET a"
            + " LEFT OUTER JOIN M_Product p ON (a.M_Product_ID=p.M_Product_ID)"
            + " LEFT OUTER JOIN C_BPartner bp ON (a.C_BPartner_ID=bp.C_BPartner_ID)"
            + " LEFT OUTER JOIN AD_User u ON (a.AD_User_ID=u.AD_User_ID)";

        // Array of Column Info    
        public static Info_Column[] _assetLayout = {
		new Info_Column("A_Asset_ID", "a.A_Asset_ID", typeof(IDColumn)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "Value"), "a.Value", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "Name"), "a.Name", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "M_Product_ID"), "p.Name", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "C_BPartner_ID"), "bp.Name",  typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "AD_User_ID"), "u.Name", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "AssetServiceDate"), "a.AssetServiceDate", typeof(DateTime)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "GuaranteeDate"), "a.GuaranteeDate", typeof(DateTime)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "VersionNo"), "a.VersionNo", typeof(String))
	};
        #endregion

        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="frame">frame</param>
        /// <param name="modal">modal</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="A_Asset_ID">asset</param>
        /// <param name="value">Query Value or Name if enclosed in @</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="whereClause">where clause</param>
        public InfoAsset(Object frame, bool modal, int WindowNo, int A_Asset_ID, String value, bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "a", "A_Asset_ID", multiSelection, whereClause)
        {
            _queryValue = value;
            log.Info(value + ", ID=" + A_Asset_ID + ", WHERE=" + whereClause);
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoAsset", true));
            //
            StatInit();
            InitInfo(_queryValue, A_Asset_ID, whereClause);


        }

        /// <summary>
        /// Get Layout
        /// </summary>
        /// <returns>array of Column_Info</returns>
        protected override Info_Column[] GetInfoColumns()
        {
            return _assetLayout;
        }

        /// <summary>
        /// Set InfoOrder Form LayOut by overriding base class design
        /// </summary>
        public override void Init()
        {
            InitializeComponent();
            base.outerPanel.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        /// <summary>
        /// Static Setup - add fields to parameterPanel
        /// </summary>
        private void StatInit()
        {
            InfoSetting();

            base.SetBusy(true);

            lblKeyValue.Content = Msg.GetMsg(Envs.GetContext(), "Value");
            lblName.Content = Msg.GetMsg(Envs.GetContext(), "Name");
            lblBPartner_ID.Content = Msg.Translate(Envs.GetContext(), "BPartner");
            lblProduct_ID.Content = Msg.Translate(Envs.GetContext(), "Product");

            Lookup _value = null;
            Lookup _valueProduct = null;



            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 8065, DisplayType.Search);
                _valueProduct = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 8047, DisplayType.Search);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(_value, _valueProduct));
            });

            //Level Controls alignment
            lblKeyValue.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblKeyValue.Margin = new Thickness(0, 0, 5, 0);

            lblBPartner_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblBPartner_ID.Margin = new Thickness(0, 0, 5, 0);

            lblName.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblName.Margin = new Thickness(0, 0, 5, 0);

            lblBPartner_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblBPartner_ID.Margin = new Thickness(0, 0, 5, 0);

            lblProduct_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblProduct_ID.Margin = new Thickness(0, 0, 5, 0);


            //value #1
            Grid.SetRow(lblKeyValue, 0);
            Grid.SetColumn(lblKeyValue, 0);
            this.tablePanel.Children.Add(lblKeyValue);

            txtValue.Height = HEIGHT;
            txtValue.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetRow(txtValue, 0);
            Grid.SetColumn(txtValue, 1);
            this.tablePanel.Children.Add(txtValue);



            //Business Partners 
            Grid.SetRow(lblBPartner_ID, 0);
            Grid.SetColumn(lblBPartner_ID, 2);
            this.tablePanel.Children.Add(lblBPartner_ID);

           


            //name #2
            Grid.SetRow(lblName, 1);
            Grid.SetColumn(lblName, 0);
            this.tablePanel.Children.Add(lblName);

            txtName.Height = HEIGHT;
            txtName.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetRow(txtName, 1);
            Grid.SetColumn(txtName, 1);
            this.tablePanel.Children.Add(txtName);


            //Porduct
            Grid.SetRow(lblProduct_ID, 1);
            Grid.SetColumn(lblProduct_ID, 2);
            this.tablePanel.Children.Add(lblProduct_ID);

            


            txtValue.KeyDown += new KeyEventHandler(KeyEvents);
            txtName.KeyDown += new KeyEventHandler(KeyEvents);

        }

        private void InvoKFunction(Lookup _value, Lookup _valueProduct)
        {
            //	From A_Asset.
            vBPartner_ID = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
            vProduct_ID = new VTextBoxButton("M_Product_ID", false, false, true, DisplayType.Search, _valueProduct);

            vBPartner_ID.Height = HEIGHT;
            vBPartner_ID.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetRow(vBPartner_ID, 0);
            Grid.SetColumn(vBPartner_ID, 3);
            this.tablePanel.Children.Add(vBPartner_ID);

            vProduct_ID.Height = HEIGHT;
            vProduct_ID.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetRow(vProduct_ID, 1);
            Grid.SetColumn(vProduct_ID, 3);
            this.tablePanel.Children.Add(vProduct_ID);

            var count = 0;
            if (vdgvRecords.ItemsSource != null)
            {
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }
            base.SetStatusMsg(count.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            //	AutoQuery
            if (_queryValue != null && _queryValue.Length > 0)
            {
                ExecuteQuery();
            }
            _LoadedOK = true;
            //	Focus
            txtValue.Focus();
            base.SetBusy(false);
        }

        /// <summary>
        /// Sets the display setting
        /// </summary>
        protected void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(35, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            //parameter panel   
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }

        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <param name="value">value</param>
        /// <param name="A_Asset_ID"></param>
        /// <param name="whereClause">where clause</param>
        private void InitInfo(String value, int A_Asset_ID, String whereClause)
        {
            //	Create Grid
            StringBuilder where = new StringBuilder();
            where.Append("a.IsActive='Y'");
            if (whereClause != null && whereClause.Length > 0)
            {
                where.Append(" AND ").Append(whereClause);
            }
            PrepareTable(_assetFROM,
                where.ToString(),
                "a.Value");

            //  Set Value
            if (value == null)
            {
                value = "%";
            }
            if (!value.EndsWith("%"))
            {
                value += "%";
            }
        }

        string textValue = "";
        string textName = "";
        object bPartner = null;
        object product = null;

        /// <summary>
        /// Construct SQL Where Clause and define parameters.
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>WHERE clause</returns>
        public override String GetSQLWhere()
        {
            StringBuilder sql = new StringBuilder();
            //	=> Value
            if (!(textValue.Equals("") || textValue.Equals("%")))
            {
                sql.Append(" AND UPPER(a.Value) LIKE @param1");
            }
            //	=> Name
            if (!(textName.Equals("") || textName.Equals("%")))
            {
                sql.Append(" AND UPPER(a.Name) LIKE @param2");
            }
            // =>C_BPartner_ID
            if (bPartner != null && bPartner != DBNull.Value)
            {
                sql.Append(" AND a.C_BPartner_ID=").Append(bPartner);
            }
            //	M_Product_ID
            if (product != null && product != DBNull.Value)
            {
                sql.Append(" AND a.M_Product_ID=").Append(product);
            }
            //
            return sql.ToString();
        }

        private void SetValuesOfControl()
        {
            textValue = txtValue.Text.Trim().ToUpper();
            textName = txtName.Text.Trim().ToUpper();
            bPartner = vBPartner_ID.GetValue();
            product = vProduct_ID.GetValue();
        }

        /// <summary>
        /// Set Parameters for Query
        /// (as defined in getSQLWhere)
        /// </summary>
        /// <param name="pstmt"></param>
        /// <param name="forCount">for counting records</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            int paramcount = 0;
            if (!(textValue.Equals("") || textValue.Equals("%")))
            {
                paramcount++;
            }
            if (!(textName.Equals("") || textName.Equals("%")))
            {
                paramcount++;
            }
            param = new SqlParameter[paramcount];
            int index = 0;
            //	=> Value
            if (!(textValue.Equals("") || textValue.Equals("%")))
            {
                if (!textValue.EndsWith("%"))
                {
                    textValue += "%";
                }
                param[index++] = new SqlParameter("@param1", textValue);
                log.Fine("Value: " + textValue);
            }
            //	=> Name
            if (!(textName.Equals("") || textName.Equals("%")))
            {
                if (!textName.EndsWith("%"))
                {
                    textName += "%";
                }
                param[index++] = new SqlParameter("@param2", textName);
                log.Fine("Name: " + textName);
            }
        }

        /// <summary>
        /// Save Selection Details
        /// Get Location/Partner Info
        /// </summary>
        public void SaveSelectionDetail()
        {
            if (vdgvRecords.SelectedItems.Count < 0)
            {
                return;
            }
            //  publish for Callout to read
            int ID = Convert.ToInt32(GetSelectedRowKey());
            Context ctx = Envs.GetContext();
            ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "A_Asset_ID", ID == null ? "0" : ID.ToString());
        }

        /// <summary>
        /// Show History
        /// </summary>
        void ShowHistory()
        {
            log.Info("InfoAsset.showHistory");
        }

        /// <summary>
        /// Has History
        /// </summary>
        /// <returns>True</returns>
        bool HasHistory()
        {
            return false;
        }

        /// <summary>
        /// Zoom
        /// </summary>
        void Zoom()
        {
            log.Info("InfoAsset.zoom");
            int A_Asset_ID = Convert.ToInt32(GetSelectedRowKey());
            if (A_Asset_ID == null)
            {
                return;
            }
            Query query = new Query("A_Asset");
            query.AddRestriction("A_Asset_ID", Query.EQUAL, A_Asset_ID);
            query.SetRecordCount(1);
            int AD_WindowNo = GetAD_Window_ID("A_Asset", true);
            //Zoom(AD_WindowNo, query);
        }

        /// <summary>
        /// Has Zoom
        /// </summary>
        /// <returns>true</returns>
        bool HasZoom()
        {
            return true;
        }

        /// <summary>
        /// Customize
        /// </summary>
        void Customize()
        {
            log.Info("InfoAsset.customize");
        }

        /// <summary>
        /// customize
        /// </summary>
        /// <returns> false</returns>
        bool HasCustomize()
        {
            return false;	//	for now
        }

        /// <summary>
        /// On key down event
        /// </summary>
        /// <param name="sender">key</param>
        /// <param name="e">current event</param>
        private void KeyEvents(object sender, KeyEventArgs e)
        {
            SetValuesOfControl();
            if (e.Key == Key.Enter)
            {
                ExecuteQuery();
            }
            else if (e.Key == Key.Down)
            {
                vdgvRecords.Focus();
            }
        }

        protected override void bRefresh_Click(object sender, RoutedEventArgs e)
        {
            SetValuesOfControl();
            ExecuteQuery();
        }

    }
}
